<?php 

function buildImageVerify($length=4, $mode='alnum', $type='png', $width=80, $height=30) 
{
    ob_start();
    $randval = random_string($mode,$length);
    $width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
    if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
        $im = imagecreatetruecolor($width, $height);
    } else {
        $im = imagecreate($width, $height);
    }
    $r = Array(225, 255, 255, 223);
    $g = Array(225, 236, 237, 255);
    $b = Array(225, 236, 166, 125);
    $key = mt_rand(0, 3);

    $backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]);    //背景色（随机）
    $borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色

    imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
    imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
    $stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
    // 干扰
    for ($i = 0; $i < 10; $i++) {
        imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
    }
    for ($i = 0; $i < 25; $i++) {
        imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
    }

    $size = floor($width / 10 * 2.2) ;
    for ($i = 0; $i < $length; $i++) {
        imagefttext($im, $size, mt_rand(1, $size/2) , ($i  - 0.5 )* $size +  floor($width / $length), floor($height / 4 * 3), $stringColor, BASEPATH.'fonts/texb.ttf', $randval{$i});
    }

    output($im, $type);
    return md5(strtolower($randval));
}

function output($im, $type='png') 
{
    ob_clean(); //防止出现'图像因其本身有错无法显示'的问题
    header("Content-type: image/" . $type);

    $ImageFun = 'image' . $type;
    $ImageFun($im);

    imagedestroy($im);
}

